import TButton from 't/basic/button';
import TIcon from 't/basic/icon';
import TItem from 't/basic/item';
import TItemSection from 't/basic/item-section';
import TList from 't/basic/list';
import TMenu from 't/basic/menu';
import TSelect from 't/basic/select';
import TmDialog from 't/basic/dialog';
import { useQuasar } from '@teld/q-components';
import TSearch from 't/basic/input';

import TInput from 't/basic/input';
import SelectHelper from 't/bussiness/select-helper';
import useMappingProps from 't/common/hooks/useMappingProps';
import TCard from 't/basic/card';
import TCardSection from 't/basic/card/CardSection';
import TCardActions from 't/basic/card/CardActions';
import TSpace from 't/basic/space';
import TChips from 't/basic/chips';
import { planChangeNotify as PlanChangeNotify } from './hock/usePlanChangeNotify';
import { shareComponent as ShareComponent } from './hock/useShareComponent';
import { usePlanAuthority } from './hock/usePlanAuthority';
import { usePlanOperateComponent } from './hock/usePlanOperateComponent';
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  ref,
  toRefs,
} from 'vue';
import './index.scss';
import Plan from './queryplan/queryPlan';
import queryPlanComponent from '../m/queryplan/queryPlan';
import subWarning from './queryplan/subWarning';
//注册hock
import { useVariable } from './hock/useVariable';
import { useUserProfile } from './hock/useUserProfile';
import { usePlanApi } from './hock/usePlanApi';
import { usePlanBaseApi } from './hock/usePlanBaseApi';
import { useKeyboardEvent } from './hock/useKeyboardEvent';
//
export const queryPlanProps = {
  dataQuery: [String, Object],
  isDev: Boolean,
  showSubWarning: String,
  pageID: String,
  mixViewGetScheme: Function,
  mixViewSetScheme: Function,
  filterGetScheme: Function,
  filterSetScheme: Function,
  query: Function,
  mixViewRefreshByData: Function,
  filterCheckMust: Function,
  fields: Array,
  pageName: String,
  pageCode: String,
  pageID: String,
  instanceCode: String,
  filterInstance: Object,
  mixViewInstance: Object,
  showTips: String,
  conditionalcolumn: Array,
  tabIndex: {
    type: Number || String,
    default: 1,
  },
  conditionalcolumn: Array,
  filtercomponent: String,
  mixedviewcomponent: String,
  visible: {
    type: Boolean,
    default() {
      return true;
    },
  },
  planType: {
    type: [String, Number],
    defalut: 0,
  },
  portalComponent: {
    type: String,
    defalut: '',
  },
};
export default defineComponent({
  name: 'TQueryPlanP',
  components: {
    TButton,
    TMenu,
    TList,
    TItem,
    TItemSection,
    TSelect,
    Plan,
    TmDialog,
    subWarning,
    SelectHelper,
    TIcon,
    TCard,
    TCardSection,
    TCardActions,
    TSpace,
    TChips,
    queryPlanComponent,
    TSearch,
    TInput,
  },
  props: {
    ...queryPlanProps,
  },

  emits: ['change', 'changed', 'beforeQuery', 'planBeEdit'],
  setup(props, { emit, attrs, expose, refs }) {
    const useVariableData = useVariable(props, emit);
    const {
      menuContent,
      Ignore,
      planIsChange,
      changePlanFlag,
      showShare,
      selectHelper,
      sharePlan,
      subPlan,
      openSubWarning,
      showDialog,
      isDefault,
      isPublic,
      saveAsPlan,
      $q,
      showNotify,
      mappingExpose,
      mappingProps,
      fields,
      pageCode,
      pageName,
      pageID,
      targetName,
      queryPlanList,
      searchFilter,
      currectPlan,
      modifyPlan,
      isSearch,
      sortCode,
      planName,
      dataQuery,
      showShareDetil,
      UserProfile,
      shareDetile,
      proxyPlan,
      renameProxy,
      showRenameDialog,
      isReset,
      refPlan,
      queryPlan_list,
      isIgnore,
      dataQueryID,
      mixViewRefreshByData,
      PortalIsChange,
      planIsChanging,
      showPopup,
    } = useVariableData;

    const { planChangeNotify, renameDialog, saveAsComponent } =
      PlanChangeNotify(useVariableData, emit);
    const { shareComponent, shareDetilComponent } = ShareComponent(
      useVariableData,
      emit,
    );
    const { hasAuth, getSubStatus, queryPlanByFilter } =
      usePlanAuthority(useVariableData);
    const {
      setUserProfile,
      setPageProfile,
      getPageUserProfile,
      getUserProfile,
    } = useUserProfile(UserProfile, modifyPlan, pageID);
    const {
      filterExpression,
      sortExpression,
      getQueryPlanList,
      OnChangeToPublishOtherComponents,
      UpdateQueryPlan,
      CreateOrUpdateQueryPlan,
      TopQueryPlan,
      SaveQueryPlans,
      deleteQueryPlan,
      updateAdvQuery,
      shareToOther,
      queryPlanByOtherComponent,
      synchronizationMixView,
      synchronizationFilter,
      resetMixViewSort,
      planOperate,
      queryPlanSave,
      queryPlanSaveAs,
      publishDataToPortal
    } = usePlanApi(useVariableData, emit);
    const { getDefaultPlan } = usePlanBaseApi(useVariableData, emit, pageID);
    useKeyboardEvent(useVariableData);

    const { generatePlanOperateComponent } = usePlanOperateComponent(
      useVariableData,
      emit,
    );
    const render = () => {
      if (!mappingProps.visible) {
        return '';
      }
      return (
        <span
          class={'queryplan_p'}
          style={`height:32px;transform: scale(1);z-Index:1000`}
          tabindex={mappingProps.tabIndex}
        >
          <span
            ref={refPlan}
            class={'queryplan_p_content'}
            style={'position:relative'}
            onClick={() => {
              if (
                ($q.screen.xs || $q.platform.is.mobile) &&
                mappingProps.planType == '1'
              ) {
                return menuContent.value.show();
              }
            }}
          >
            <i class='fas icon icon-t-search-scheme1 queryplan_p_icon'></i>
            <span class={'queryplan_p_plan_name'}>
              {mappingProps.isDev ? '视图方案' : planName.value}
            </span>
            <i
              class={`${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowDown ?? 'icon-t-arrow-down'}`}
              style={'font-size:10px !important;color: rgba(0, 0, 0, .56);'}
            ></i>
          </span>

          {(() => {
            if (
              (PortalIsChange.value || planIsChange.value) &&
              !isIgnore.value &&
              Ignore.value &&
              modifyPlan.value &&
              modifyPlan.value.ID &&
              mappingProps.showTips != '0'
            ) {
              return planChangeNotify(useVariableData);
            }
          })()}
          {generatePlanOperateComponent()}
          {/* 分享详情 */}
          {shareDetilComponent(useVariableData)}
          {/* 分享组件 */}
          {shareComponent(useVariableData)}
          {/* 重命名 */}
          {renameDialog(useVariableData)}
          {/* 另存 */}
          {saveAsComponent(useVariableData)}
          {(() => {
            if (openSubWarning.value) {
              return (
                <subWarning
                  filterServer={fields.value}
                  dataQuery={dataQuery.value}
                  modifyPlan={subPlan.value}
                  v-model:showSubWarning={openSubWarning.value}
                  pageID={pageID.value}
                  pageCode={pageCode.value}
                  pageName={pageName.value}
                  targetDom={refPlan}
                  onSubWarning={async e => {
                    let plan = Object.assign({}, subPlan.value);
                    if (e == 'cancel') {
                      delete plan.WarningID;
                      UpdateQueryPlan(plan, {
                        WarningID: '',
                      }).then(async res => {
                        queryPlanList.value = await getQueryPlanList();
                        if (subPlan.value.ID == modifyPlan.value.ID) {
                          modifyPlan.value.WarningID = '';
                          if (proxyPlan.value) {
                            proxyPlan.value = JSON.stringify(modifyPlan.value);
                          }
                        }
                        emit('changed', {
                          hasAuth: hasAuth(),
                          status: getSubStatus(),
                        });
                      });

                      return;
                    }
                    if (e) {
                      UpdateQueryPlan(plan, {
                        WarningID: e,
                      }).then(async res => {
                        queryPlanList.value = await getQueryPlanList();
                        if (subPlan.value.ID == modifyPlan.value.ID) {
                          modifyPlan.value.WarningID = e;
                          if (proxyPlan.value) {
                            proxyPlan.value = JSON.stringify(modifyPlan.value);
                          }
                        }
                        emit('changed', {
                          hasAuth: hasAuth(),
                          status: getSubStatus(),
                        });
                      });
                    }
                  }}
                ></subWarning>
              );
            } else {
              return '';
            }
          })()}
        </span>
      );
    };

    const init = () => {
      if (!props.isDev) {
        getQueryPlanList().then(res => {
          queryPlanList.value = res;
          getDefaultPlan();
        });
      } else {
        getDefaultPlan();
      }
    };
    if (window.Funcs&&!props.isDev) {
      try {
        getUserProfile([
          {
            Key: UserProfile.UserProfileKey,
            DynamicKey: UserProfile.UserDynamicKeys_notify,
          },
          {
            Key: UserProfile.UserProfileKey,
            DynamicKey: UserProfile.UserDynamicKeys_sort,
          },
          // {
          //   Key: UserProfile.UserProfileKey,
          //   DynamicKey: UserProfile.UserDynamicKeys_unfolder,
          // },
        ])
          .then(res => {
            res.data.forEach(item => {
              if (item.DynamicConfigKey == UserProfile.UserDynamicKeys_notify) {
                Ignore.value = item.ConfigValue === '0' ? false : true;
              }
              if (
                item.DynamicConfigKey == UserProfile.UserDynamicKeys_sort &&
                item.ConfigValue
              ) {
                sortCode.value = item.ConfigValue;
              }
            });
            init();
          })
          .catch(() => {
            init();
          });
      } catch (error) {
        init();
      }
    } else {
      init();
    }

    window.addEventListener('pageshow', function (event) {
      if (event.persisted) {
        // 页面是从缓存中加载的
        queryPlanByOtherComponent();
      }
    });
    const QueryPlanFnList = {
      Query: queryPlanByOtherComponent,
      query: queryPlanByOtherComponent,
      updateAdvQuery,
      filterExpression,
      sortExpression,
      queryPlanSave,
      queryPlanSaveAs,
      openWarnSub: () => {
        subPlan.value = modifyPlan.value;
        openSubWarning.value = true;
      },
      setUserProfileByMixView: params => {
        return setPageProfile(params);
      },
      resetMixViewSort,
      savePortalPlanContent: async (callback, status) => {
        let IsAuth = hasAuth();
        let isSave = false;
        if (!status || (status && status.isSave)) {
          isSave = true;
        }
        if (IsAuth && isSave && modifyPlan.value.IsSystem&&modifyPlan.value.DefaultPortalId=='') {
          //1。存储方案
          //2.更新门户
          window.saveAsCallback = callback;
          queryPlanSave(true);
        } else if (IsAuth && isSave) {
          //保存
          let ID = await callback();
          if (ID) {
            ID = ID.data;
          }
          if (ID != modifyPlan.value.PortalId) {
            modifyPlan.value.PortalId = ID;
          }
          queryPlanSave(true);
          return;
        } else {
          //另存
          queryPlanSaveAs(callback, true);
        }
        //如果是保存
        /**
         * 1.存储门户
         * 2.存储方案
         */

        //如果是另存
        /**
         * 先存储方案
         */
      },
      PortalChanged: res => {
        if (planIsChanging.value) return;
        PortalIsChange.value = res;
        if (res) {
          emit('changed', {
            hasAuth: hasAuth(),
            status: getSubStatus(),
          });
        }
      },
      publishDataToPortal:publishDataToPortal?publishDataToPortal:()=>{}
    };
    onMounted(() => {
      if (window.Widget[mappingProps.portalComponent]) {
        window.Widget[
          mappingProps.portalComponent
        ].rejestorAdvanceQueryComponent({
          ...mappingExpose,
          ...QueryPlanFnList,
        });
      }
    });
    expose(Object.assign(mappingExpose, QueryPlanFnList));
    return render;
  },
});
